// hello/middleware/jwt_middleware.go
package middleware

import (
	"net/http"
	"strings"

	"github.com/gin-gonic/gin"
	"hello/utils"
)

// JWTAuthMiddleware JWT身份验证中间件
func JWTAuthMiddleware() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		// 从请求头中获取Authorization字段
		authHeader := ctx.GetHeader("Authorization")
		if authHeader == "" {
			ctx.JSON(http.StatusUnauthorized, utils.JSONResult{
				Code:    http.StatusUnauthorized,
				Message: "未提供授权信息",
				Data:    nil,
			})
			ctx.Abort()
			return
		}

		// 解析Authorization字段
		parts := strings.SplitN(authHeader, " ", 2)
		if len(parts) != 2 || parts[0] != "Bearer" {
			ctx.JSON(http.StatusUnauthorized, utils.JSONResult{
				Code:    http.StatusUnauthorized,
				Message: "授权信息格式错误",
				Data:    nil,
			})
			ctx.Abort()
			return
		}

		// 验证JWT
		tokenString := parts[1]
		userID, err := utils.ValidateToken(tokenString)
		if err != nil {
			ctx.JSON(http.StatusUnauthorized, utils.JSONResult{
				Code:    http.StatusUnauthorized,
				Message: "无效的令牌: " + err.Error(),
				Data:    nil,
			})
			ctx.Abort()
			return
		}

		// 将用户ID存储到上下文
		ctx.Set("user_id", userID)
		ctx.Next()
	}
}
